<template>
    <div class="add-article-container">
        <div class="split-pane">
            <div class="pane left" v-show="true" ref="left">
                <h3 style="text-align: center;">预览</h3>
                <div style="height: calc(100vh - 110px); overflow-y: scroll;" ref="htmlRef"></div>
            </div>
            <div class="resizer" ref="resizer"></div>
            <div class="pane right" ref="right">
                <!-- <p>右侧区域内容</p> -->
                <Toolbar class="toolbar" style="border-bottom: 1px solid #ccc" :editor="editorRef"
                    :defaultConfig="toolbarConfig" :mode="mode" />
                <Editor class="editor" v-model="valueHtml" :defaultConfig="editorConfig" @onChange="handleChange"
                    :mode="mode" @onCreated="handleCreated" />

                <div class="bottom">
                    <p>选中文字：{{ selectLength }}</p>
                    <p>全部文字：{{ allLength }}</p>
                </div>

            </div>
        </div>
        <div class="article-right">
            <h3>文章信息</h3>
            <el-form :model="form" label-width="auto" style="max-width: 600px" :label-position="'top'" :rules="rules"
                ref="formRef">
                <el-form-item label="标题" prop="title">
                    <el-input v-model="form.title" type="textarea" placeholder="请输入标题" />
                </el-form-item>
                <el-form-item label="简介" prop="summary">
                    <el-input v-model="form.summary" type="textarea" placeholder="请输入简介" />
                </el-form-item>
                <el-form-item label="封面" prop="cover">
                    <!-- <el-input v-model="form.cover" /> -->
                    <el-upload class="avatar-uploader" :action="baseUrl + '/api/upload'" :show-file-list="false"
                        :on-success="handleAvatarSuccess" method="POST" nam="file"
                        :headers="{ Authorization: getToken('token') }" :before-upload="beforeAvatarUpload">
                        <img v-if="form.cover" :src="srcToPath(form.cover)" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
                <el-form-item label="类别/标签" prop="category">
                    <el-select v-model="form.category" multiple filterable allow-create default-first-option
                        multiple-limit="5" :reserve-keyword="false" placeholder="请选择分类">
                        <el-option v-for="item in categoryList" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>

            </el-form>
            <el-button style="width: 100%;" type="primary" @click="commitArticle">保存</el-button>
        </div>
    </div>
</template>
<script setup>
// 导入Store
import { onBeforeUnmount, ref, shallowRef, onMounted, watch, unref, reactive } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { baseUrl } from '@/utils/http.js'
import { getCategory } from '@/api/main.js'
import { updateArticle, getMyArticleDetial } from '@/api/article'
import { ElMessage } from 'element-plus'
import { getToken } from '@/utils/auth.js'

import srcToPath from '@/utils/srcToPath.js'
const resizer = ref(null)
const left = ref(null)
const right = ref(null)
const htmlRef = ref(null)
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
import { useRouter, useRoute } from 'vue-router';
const router = useRouter()
const route = useRoute()
const id = ref(route.params.id)

const form = ref({
    cover: "",
    summary: "",
    title: ""
})
const formRef = ref(null)
const rules = reactive({
    title: [
        { required: true, message: '请填写标题', trigger: 'blur' },
    ],
    summary: [
        { required: true, message: '请填写简介', trigger: 'blur' },
    ],
    cover: [
        { required: true, message: '请上传封面', trigger: 'blur' },
    ],
    category: [
        { required: true, message: '请上传封面', trigger: 'blur' },
    ],
})

// 内容 HTML
const valueHtml = ref('模拟')
const selectLength = ref(0)
const allLength = ref(0)
// import { getToken } from '@/utils/auth.js'
const toolbarConfig = {}
const editorConfig = {
    placeholder: '请输入内容...',
    MENU_CONF: {
        uploadImage: {
            server: '/api/api/upload',
            fieldName: 'file',
            // 自定义增加 http  header
            headers: {
                Authorization: getToken('token')
            },

            base64LimitSize: 5 * 1024, // 10kb
            customInsert(res, insertFn) {  // TS 语法
                // customInsert(res, insertFn) {                  // JS 语法
                // res 即服务端的返回结果
                console.log(res, insertFn);
                // 从 res 中找到 url alt href ，然后插入图片
                insertFn(baseUrl + '/' + res.path, res.filename, baseUrl + '/' + res.path)
            },
        }
    }
}
const handleChange = (editor) => {            // JS 语法
    // editor changed
    console.log('content', editor.children)
    // 选中文字
    const selectionText = editorRef.value.getSelectionText()
    selectLength.value = selectionText.length
    // 全部文字
    const text = editorRef.value.getText().replace(/\n|\r/mg, '')
    allLength.value = text.length
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
})

const handleCreated = (editor) => {
    editorRef.value = editor // 记录 editor 实例，重要！
}

// 提交文章信息
const commitArticle = async () => {
    await formRef.value.validate(async (valid, fields) => {
        if (valid) {
            if (!valueHtml.value || valueHtml.value.length == 0) {
                return ElMessage.info('请填写正文')
            }
            const res = await updateArticle({ ...unref(form), content: valueHtml.value })
            if (res.status == 200) {
                ElMessage.success('保存成功')
            }
            console.log(res);
        } else {
            ElMessage.info('请填写信息')
        }
    })

}

const handleAvatarSuccess = (
    response,
    uploadFile
) => {
    console.log(response);
    form.value.cover = response.path
}

const beforeAvatarUpload = (rawFile) => {
    const fileTypes = ["image/jpeg", "image/jpg", "image/png", "image/gif"];

    const mimeType = fileTypes.includes(rawFile.type.split('/')[1]);
    if (mimeType) {
        ElMessage.error('Avatar picture must be jpeg|jpg|png|gif format!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('Avatar picture size can not exceed 2MB!')
        return false
    }
    return true
}

let timer = null
watch(valueHtml, (newV, oldV) => {
    if (timer) {
        clearTimeout(timer)
        timer = null
    }
    timer = setTimeout(() => {
        console.log(newV);
        htmlRef.value.innerHTML = newV

    }, 500)
})

const categoryList = ref([])
// 初始化
const init = async () => {
    // 分类列表
    const category = await getCategory()
    categoryList.value = category.data

    // 获取本文章信息
    const res = await getMyArticleDetial(id.value);
    if (res.status != 200) {
        return router.push('/personal')
    }
    form.value = res.data.article
    form.value.category = res.data.categoryList.map(item => item.id)
    valueHtml.value = form.value.content
    console.log(res);
}

onMounted(() => {
    myMove()
    init()
})

const editorH = ref(0)
// 计算编辑器高度
const editorHeight = () => {
    editorH.value = editorRef.value.offsetHeight + 120
}

// 拖动事件
const myMove = () => {
    let isResizing = false;
    let startX;
    let leftPaneWidth;

    resizer.value.addEventListener('mousedown', function (e) {
        isResizing = true;
        startX = e.clientX;
        leftPaneWidth = parseFloat(window.getComputedStyle(left.value).width);

        document.addEventListener('mousemove', onMouseMove);
        document.addEventListener('mouseup', onMouseUp);
        document.addEventListener('mouseleave', onMouseUp); // 添加mouseleave事件，以防鼠标移出窗口时未释放  
    });

    function onMouseMove(e) {
        if (!isResizing) return;
        e.preventDefault();
        const shiftX = e.clientX - startX;
        const newWidth = Math.max(50, leftPaneWidth + shiftX); // 最小宽度设置为50，防止过小  
        left.value.style.flexBasis = newWidth + 'px';
        right.value.style.flexBasis = 'calc(100% - ' + (newWidth + 10) + 'px)'; // 加上调整器的宽度  
    }

    function onMouseUp() {
        isResizing = false;
        document.removeEventListener('mousemove', onMouseMove);
        document.removeEventListener('mouseup', onMouseUp);
        document.removeEventListener('mouseleave', onMouseUp);
    }
}


</script>

<style lang="scss" scoped>
.add-article-container {
    display: flex;
    justify-content: start;
    align-items: start;
    height: calc(100vh - 60px);

    .split-pane {
        width: 100%;
        display: flex;
        height: 100%;
    }

    .pane {
        position: relative;
        flex: 1;
        overflow: auto;

    }

    .left,
    .right {
        flex: 1 1 auto;
        /* 使得元素默认平分空间 */
        flex-basis: 50%;
        /* 初始时各占一半 */
        height: calc(100vh - 60px);
        position: relative;
        overflow-y: hidden;

        .toolbar {
            position: sticky;
            z-index: 99;
            background-color: var(--el-bg-color);
        }

        .editor {
            max-height: calc(80vh);
            background-color: var(--el-bg-color);
        }

        .bottom {
            width: 100%;
            position: absolute;
            bottom: 0;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
    }

    .resizer {
        flex: 0 0 10px;
        /* 调整器宽度固定为10px */
        cursor: col-resize;
        z-index: 1;
        background-color: var(--el-color-primary-light-7);
        /* 可以添加一些样式来改善用户体验，比如鼠标悬停时的效果 */
    }

    .article-right {
        width: 300px;
        padding: 10px;

        h3 {
            text-align: center;
        }

        .avatar-uploader .el-upload {
            border: 1px dashed var(--el-border-color);
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
            transition: var(--el-transition-duration-fast);
        }

        .avatar-uploader .el-upload:hover {
            border-color: var(--el-color-primary);
        }

        .el-icon.avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 178px;
            height: 178px;
            text-align: center;
        }

        .avatar-uploader .avatar {
            width: 178px;
            height: 178px;
            display: block;
        }
    }
}
</style>